#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void _tree2str(TreeNode* root, string& ret)
    {
        if (root == nullptr)
            return;

        char in[6];
        sprintf(in, "%d", root->val);
        ret.append(in);
        ret.push_back('(');
        _tree2str(root->left, ret);
        ret.append(")(");
        _tree2str(root->right, ret);
        ret.push_back(')');
    }
    string tree2str(TreeNode* root) {
        string ret;
        string str;
        _tree2str(root, str);
        size_t n = str.size();
        for (int i = 0; i < n - 1; i++)
        {
            if ((str[i] == '(' && str[i + 1] == ')') && (i >= n - 3 || (str[i + 3] == ')' || str[i + 3] == '(')))
                str[i] = str[i + 1] = ' ';
        }
        for (auto& c : str)
        {
            if (c != ' ')
                ret.push_back(c);
        }
        return ret;
    }
};